<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--              <el-form-item label="月份" prop="month">
                <el-date-picker
                    v-model="queryParams.month"
                    type="month"
                    value-format="YYYY-MM-DD"
                    placeholder="选择月">
                </el-date-picker>
              </el-form-item>-->
              <el-form-item label="区域" prop="regionId">
                <el-cascader :options="qxoptions" v-model="queryParams.regionId" :props="{ emitPath: false }"  filterable placeholder="请搜索或选择区域" @keyup.enter="handleQuery" :show-all-levels="false"></el-cascader>
                <!--                <el-input v-model="queryParams.name" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
              </el-form-item>
              <el-form-item label="门店名称" prop="storeName">
                <el-input v-model="queryParams.storeName" placeholder="请输入门店名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="店长姓名" prop="managerName">
                <el-input v-model="queryParams.managerName" placeholder="请输入店长姓名" clearable @keyup.enter="handleQuery" />
              </el-form-item>
<!--              <el-form-item label="手机号" prop="managerPhone">
                <el-input v-model="queryParams.managerPhone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="审核状态" prop="status" style="width: 220px">
                <el-select v-model="queryParams.status" placeholder="请选择审核状态">
                  <el-option label="未审核" value="0"></el-option>
                  <el-option label="已审核" value="1"></el-option>
                  <el-option label="已驳回" value="2"></el-option>
                </el-select>
              </el-form-item>-->

              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:stoer:add']">新增</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-form-item label="选择导出时间段" style="font-weight: 600;">
                  <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
               </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:invoice:export']">默认导出上个月</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
<!--              <el-table-column label="月份" align="center" key="month" prop="month"  />-->
              <el-table-column label="区域" align="center" key="regionName" prop="regionName"  />
              <el-table-column label="门店名称" align="center" key="storeName" prop="storeName"  />
              <el-table-column label="店长姓名" align="center" key="managerName" prop="managerName"  />
<!--              <el-table-column label="联系方式" align="center" key="managerPhone" prop="managerPhone"  />-->
              <el-table-column label="最新上传时间" align="center" key="updateTime" prop="updateTime"  />
              <el-table-column label="门店系统费(元)" align="center" key="feeAmount" prop="feeAmount"  />
<!--              <el-table-column label="审核状态" align="center" width="100" prop="status" >
                <template #default="scope">
                  {{  scope.row.status === 0 ? '未审核' :
                    scope.row.status === 1 ? '已审核' :
                        scope.row.status === 2 ? '已驳回' :
                            '未知状态' }}
                </template>
              </el-table-column>-->
<!--              <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" v-if="scope.row.status == 0" @click="handleStatusChange(scope.row)" v-hasPermi="['system:invoice:reject']">驳回</el-button>
                  <el-button link type="primary" v-if="scope.row.status != 1" @click="handQueren(scope.row)" v-hasPermi="['system:invoice:confirm']">审核</el-button>

                </template>
              </el-table-column>-->
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-col :span="24">
          <el-form-item label="所属门店">
            <el-select v-model="form.storeId" filterable placeholder="请搜索或选择所属门店">
              <el-option
                  v-for="item in listStores"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 系统费用列表 -->
        <el-col :span="24">
          <el-form-item label="系统费">
            <div
                v-for="(fee, index) in form.systemFees"
                :key="index"
                class="fee-item"
                :prop="'systemFees.' + index + '.value'"
                :rules="feeRules"
            >
              <el-row :gutter="12">
                <el-col :span="16">
                  <el-form-item>
                    <el-input
                        type="number"
                        v-model="fee.value"
                        placeholder="请输入系统费"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" style="width:200px;display: flex;align-items: center;">
                  <el-button type="primary" size="small" plain icon="Plus"  @click="addFee"  v-show="index === form.systemFees.length - 1">新增</el-button>
                  <el-button plain type="danger" size="small" icon="Delete" @click="removeFee(index)"  v-if="form.systemFees.length > 1">删除</el-button>

                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-col>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情 -->

    <el-dialog title="查看系统费" v-model="infoopen" width="1000px" append-to-body>
      <div class="contract-container">

        <!-- 基本信息表格 -->
        <el-table :data="[htdata]" border class="info-table">
          <el-table-column label="月份" prop="month"></el-table-column>
          <el-table-column label="区域" prop="regionName"></el-table-column>
          <el-table-column label="门店名称" prop="storeName"></el-table-column>
          <el-table-column label="店长姓名" prop="managerName"></el-table-column>
          <el-table-column label="联系方式" prop="managerPhone"></el-table-column>

<!--          <el-table-column label="联系方式" prop="managerPhone"></el-table-column>-->
          <el-table-column label="最新上传时间" prop="updateTime"></el-table-column>
          <el-table-column label="审核状态" prop="status">
            <template #default="{row}">
              {{ row.status === 0 ? '未审核' :
                row.status === 1 ? '已审核' :
                    row.status === 2 ? '已驳回' :
                        '未知状态' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="{row}">
              <el-button link type="primary" v-if="row.status == 0"   @click="handleStatusChange(row)" v-hasPermi="['system:invoice:reject']">驳回</el-button>
              <el-button link type="primary" v-if="row.status == 0" @click="handQueren(row)" v-hasPermi="['system:invoice:confirm']">确认</el-button>

            </template>
          </el-table-column>
        </el-table>
        <div class="demo-image__lazy" style="width:70%;margin: 0 auto;">
          <el-image v-for="url in urls" :key="url" :src="url" lazy :preview-src-list="urls"></el-image>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-form ref="upload.form" :rules="upload.rules" :model="upload.form" label-width="80px">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input type="textarea" v-model="upload.form.rejectReason" ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="quxiao">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth"
import useAppStore from '@/store/modules/app'
import {
  listUser,
  getContract,
  selectTreeStore,
  selectRoleAll,
  getStorechange,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
  listStore,
  blacklist, invoiceConfirm,
  feeUpload
} from "@/api/storeUpload/systemFee.js"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {addContract, editContract} from "@/api/contract/contractList.js";
// import {selectRoleAll} from "../../../api/company/store.js";

const router = useRouter()
const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex,sys_company_disable} = proxy.useDict("sys_normal_disable", "sys_user_sex","sys_company_disable")
const userList = ref([])
const tableData = ref([])
const qxoptions = ref([])
const open = ref(false)
const bgopen = ref(false)
const infoopen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const names = ref([])
const listStores = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const htdata = ref('')
const dateRange = ref([])
const deptName = ref("")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const postOptions = ref([])
const roleOptions = ref([])
const urls = ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,

  // 弹出层标题（用户导入）
  title: "",
  form:{
    rejectReason:undefined
  },
  rules:{
    rejectReason: [
      { required: true, message: '请输入原因', trigger: 'blur' }
    ],
  }
})
const userRef = ref(null); // 表单引用
// 表单数据
const form = reactive({
  storeId: '',
  systemFees: [{ value: '' }] // 初始一个空的系统费
})
const data = reactive({

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    storeName: undefined,
    createTime:undefined,
    startTime:undefined,
    endTime:undefined,
    status:undefined
  },

})

const { queryParams } = toRefs(data)

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

// 系统费验证规则
const feeRules = [
  { required: true, message: '系统费不能为空', trigger: 'blur' },
  {
    validator: (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        callback(new Error('系统费不能为空'));
      } else if (isNaN(Number(value))) {
        callback(new Error('请输入有效的数字'));
      } else if (Number(value) < 0) {
        callback(new Error('系统费不能为负数'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }
];

// 添加系统费
const addFee = () => {
  form.systemFees.push({ value: '' });
};

// 删除系统费
const removeFee = (index) => {
  form.systemFees.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    await userRef.value.validate();

    // 检查所有系统费是否已填写且有效
    const hasInvalidFee = form.systemFees.some(fee => {
      return fee.value === '' || fee.value === null || isNaN(Number(fee.value));
    });

    if (hasInvalidFee) {
      proxy.$modal.msgError("请填写所有有效的系统费用")
      // ElMessage.error('请填写所有有效的系统费用');
      return;
    }

    // 表单验证通过，提交逻辑
    console.log('提交数据:', form);
    const requestData = {
      storeId: form.storeId,
      systemFees: form.systemFees
    };
    feeUpload(requestData).then(res => {
      console.log(res)
      open.value = false;
      // resetForm();
      proxy.$modal.msgSuccess("提交成功");
      resetQuery()
    })


  } catch (error) {
    console.error('表单验证失败:', error);
  }
};


/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val)
})
/** 查询区域下拉列表 */
function getselectTreeStore() {
  selectTreeStore().then(res => {
    console.log(res)
    qxoptions.value = res.data
  })
}
/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}


/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {

  queryParams.value =[]
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined
  // proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.name || names.value
  proxy.$modal.confirm('是否确认删除门店名称为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  console.log(dateRange)
  let data = {};
  if(dateRange.value){
    data.beginTime = dateRange.value[0], data.endTime = dateRange.value[1]
  }
  proxy.download("system/fee/export", data,`user_${new Date().getTime()}.xlsx`)
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row)
      break
    case "handleAuthRole":
      handleAuthRole(row)
      break
    default:
      break
  }
}


/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  names.value = selection.map(item => item.name)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 点击确认  */
function handQueren(row) {
  let text = row.status === "0" ? "启用" : "停用"
  proxy.$modal.confirm('确认要审核门店系统费为'+ row.feeAmount +'元的该数据吗？').then(function () {
    return invoiceConfirm(row.id)
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("审核成功")
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0"
  })
}
/** 点击驳回  */
function handleStatusChange(row) {
  console.log(row);
  const { id, isBlacklist } = row;

  upload.form.id = row.id;
  upload.form.isBlacklist = row.isBlacklist
  upload.title = '驳回'
  upload.open = true

}
/** 驳回的提交 */
function submitFileForm(row) {
  // blacklist
  proxy.$refs["upload.form"].validate((valid) => {
    if (valid) {
      console.log(upload.form)
       blacklist(upload.form).then(response => {

         upload.form.rejectReason = undefined;
         getList();
       })
    }
  });
}
/*取消*/
function quxiao(){
  upload.open = false;
  upload.form.rejectReason = undefined;
  getList();
}

/** 导入按钮操作 */
function handleImport(row) {
  upload.title = "加入黑名单"
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/store/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}



/** 重置操作表单 */
function reset() {
  form.value = {
    managerId: undefined,
    name: undefined,
    status: "",
    address: undefined,
    managerPhone: undefined,
    mangerCard: undefined,
    mangerSex: undefined,
    roleId: undefined,
    remark: undefined,
    isIncumbency: undefined,
    incumTime: undefined,
    dimissionTime: undefined,
    isFranchise: undefined,
    accountNumber: undefined,
    accountAdd: undefined,

  }
  proxy.resetForm("userRef")
}

/*查看合同*/
function handleInfo(row){

  const id = row.id
  getContract(id).then(response => {
    console.log(response)
    htdata.value = response.data
    urls.value = response.data.invoiceUrls
    infoopen.value = true
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  bgopen.value = false;
  infoopen.value = false;
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  listStore().then(res=>{
    listStores.value = res.data;
  })
  selectRoleAll().then(response => {

    postOptions.value = response.data
    console.log(response)
    open.value = true
    title.value = "添加"
    console.log(response)
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listStore().then(res=>{
    listStores.value = res.rows;
  })
  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
  const userId = row.id || ids.value
  getUser(userId).then(response => {
    form.value = response.data
    postOptions.value = response.posts
    roleOptions.value = response.roles
    form.value.postIds = response.postIds
    form.value.roleIds = response.roleIds
    open.value = true
    title.value = "修改客户"
    form.password = ""
  })
  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
}

/** 提交按钮 */
/*function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })

      }
    }
  })
}*/

onMounted(() => {
  getDeptTree()
  getList()
  getselectTreeStore()
  /*proxy.getConfigKey("sys.user.initPassword").then(response => {
    initPassword.value = response.msg
  })*/
})
</script>
<style scoped>
.fee-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.fee-item:last-child {
  margin-bottom: 0;
}
.contract-container {
  padding: 20px;
  background: #fff;
}

.contract-header {
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}

.contract-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.contract-no {
  font-size: 14px;
  color: #666;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.info-table {
  margin-bottom: 20px;
}

.person-info {
  margin: 5px 0;
}

.person-info .label {
  color: #666;
  display: inline-block;
  width: 60px;
  text-align: right;
  margin-right: 10px;
}
</style>